import type { GraphicObject } from './GraphicObject';

export interface Layer {
  id: string;
  name: string;
  visible: boolean;
  locked: boolean;
  objects: GraphicObject[];
}

export class LayerManager {
  private layers: Map<string, Layer> = new Map();
  private activeLayerId: string = 'default';

  constructor() {
    // 创建默认图层
    this.createLayer('default', '默认图层');
  }

  /**
   * 创建新图层
   */
  createLayer(id: string, name: string): Layer {
    const layer: Layer = {
      id,
      name,
      visible: true,
      locked: false,
      objects: [],
    };

    this.layers.set(id, layer);
    return layer;
  }

  /**
   * 删除图层
   */
  deleteLayer(id: string): boolean {
    if (id === 'default') {
      console.warn('Cannot delete default layer');
      return false;
    }

    if (this.layers.has(id)) {
      // 如果删除的是当前活动图层，切换到默认图层
      if (this.activeLayerId === id) {
        this.activeLayerId = 'default';
      }

      this.layers.delete(id);
      return true;
    }

    return false;
  }

  /**
   * 设置活动图层
   */
  setActiveLayer(id: string): boolean {
    if (this.layers.has(id)) {
      this.activeLayerId = id;
      return true;
    }
    return false;
  }

  /**
   * 获取活动图层
   */
  getActiveLayer(): Layer | null {
    return this.layers.get(this.activeLayerId) || null;
  }

  /**
   * 获取所有图层
   */
  getAllLayers(): Layer[] {
    return Array.from(this.layers.values());
  }

  /**
   * 获取图层
   */
  getLayer(id: string): Layer | null {
    return this.layers.get(id) || null;
  }

  /**
   * 重命名图层
   */
  renameLayer(id: string, newName: string): boolean {
    const layer = this.layers.get(id);
    if (layer) {
      layer.name = newName;
      return true;
    }
    return false;
  }

  /**
   * 设置图层可见性
   */
  setLayerVisibility(id: string, visible: boolean): boolean {
    const layer = this.layers.get(id);
    if (layer) {
      layer.visible = visible;
      return true;
    }
    return false;
  }

  /**
   * 设置图层锁定状态
   */
  setLayerLocked(id: string, locked: boolean): boolean {
    const layer = this.layers.get(id);
    if (layer) {
      layer.locked = locked;
      return true;
    }
    return false;
  }

  /**
   * 移动图层顺序
   */
  moveLayer(id: string, newIndex: number): boolean {
    const layers = this.getAllLayers();
    const currentIndex = layers.findIndex((layer) => layer.id === id);

    if (currentIndex === -1 || newIndex < 0 || newIndex >= layers.length) {
      return false;
    }

    // 重新排序图层
    const layer = layers.splice(currentIndex, 1)[0];
    layers.splice(newIndex, 0, layer);

    // 更新图层映射（按新顺序）
    this.layers.clear();
    layers.forEach((layer) => {
      this.layers.set(layer.id, layer);
    });

    return true;
  }

  /**
   * 添加对象到图层
   */
  addObjectToLayer(object: GraphicObject, layerId?: string): boolean {
    const targetLayerId = layerId || this.activeLayerId;
    const layer = this.layers.get(targetLayerId);

    if (layer && !layer.locked) {
      layer.objects.push(object);
      return true;
    }

    return false;
  }

  /**
   * 从图层移除对象
   */
  removeObjectFromLayer(object: GraphicObject, layerId?: string): boolean {
    const targetLayerId = layerId || this.activeLayerId;
    const layer = this.layers.get(targetLayerId);

    if (layer) {
      const index = layer.objects.indexOf(object);
      if (index > -1) {
        layer.objects.splice(index, 1);
        return true;
      }
    }

    return false;
  }

  /**
   * 移动对象到其他图层
   */
  moveObjectToLayer(object: GraphicObject, targetLayerId: string): boolean {
    // 从当前图层移除
    for (const layer of this.layers.values()) {
      const index = layer.objects.indexOf(object);
      if (index > -1) {
        layer.objects.splice(index, 1);
        break;
      }
    }

    // 添加到目标图层
    return this.addObjectToLayer(object, targetLayerId);
  }

  /**
   * 获取图层中的所有对象
   */
  getObjectsInLayer(layerId: string): GraphicObject[] {
    const layer = this.layers.get(layerId);
    return layer ? [...layer.objects] : [];
  }

  /**
   * 获取所有可见对象
   */
  getAllVisibleObjects(): GraphicObject[] {
    const visibleObjects: GraphicObject[] = [];

    for (const layer of this.layers.values()) {
      if (layer.visible) {
        visibleObjects.push(...layer.objects);
      }
    }

    return visibleObjects;
  }

  /**
   * 获取对象所在的图层
   */
  getObjectLayer(object: GraphicObject): Layer | null {
    for (const layer of this.layers.values()) {
      if (layer.objects.includes(object)) {
        return layer;
      }
    }
    return null;
  }

  /**
   * 序列化图层数据
   */
  serialize(): any[] {
    return this.getAllLayers().map((layer) => ({
      id: layer.id,
      name: layer.name,
      visible: layer.visible,
      locked: layer.locked,
      objectIds: layer.objects.map((obj) => obj.id),
    }));
  }

  /**
   * 从数据反序列化图层
   */
  deserialize(layerData: any[], objectMap: Map<string, GraphicObject>): void {
    this.layers.clear();

    for (const data of layerData) {
      const layer = this.createLayer(data.id, data.name);
      layer.visible = data.visible;
      layer.locked = data.locked;

      // 添加对象到图层
      for (const objectId of data.objectIds) {
        const object = objectMap.get(objectId);
        if (object) {
          layer.objects.push(object);
        }
      }
    }

    // 设置默认活动图层
    this.activeLayerId = 'default';
  }

  /**
   * 销毁图层管理器
   */
  destroy(): void {
    this.layers.clear();
  }
}

export default LayerManager;
